package net.zdreamer.geracomium.utils.httputils;

import android.os.Handler;
import android.os.Message;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;

import net.zdreamer.geracomium.application.BaseApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/1/22.
 */
public class PersonalCenterService {
    public static void RegistPost( Map<String, Object> map, String oldmanUrl, final Handler handler) {
        RequestQueue requestQueue = BaseApplication.get().getRequestQueue();
        JSONObject jsonObject = new JSONObject(map);
        System.out.println(jsonObject);
        final Message msg = new Message();
        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST,
                oldmanUrl, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("response"+response);
                        msg.arg1 = 201;
                        handler.sendMessage(msg);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println(error.networkResponse.statusCode);
                msg.arg1=401;
                handler.sendMessage(msg);
            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", BaseApplication.get().getToken());
                return headers;
            }
            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                // TODO Auto-generated method stub
                JSONObject str = null;
                String stro=null;
                try {
                    stro = new String(response.data,"utf-8");

                    str=new JSONObject(stro);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        requestQueue.add(jsonRequest);

    }
}